﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Web;

namespace MainWebService
{
    
    public class DatabaseDetails
    {
        
        public int DbId { get; set; }

        
        public string DBName { get; set; }

        
        public int CreatedBy { get; set; }

        
        public bool IsCaseSensitiveValidation { get; set; }

        
        public int RowCount { get; set; }

        
        public int MyProperty { get; set; }

        
        public DataSet GetServiceDetails { get; set; }

        
        public DateTime LastUpdated { get; set; }

        
        public string UserMessage { get; set; }

        public List<int> ServiceDetails { get; set; }

        public List<Scans> ScanDataList { get; set; }

        internal List<Scans> GetScanDataList(byte[] lstData)
        {
            //BinaryFormatter bformatter = new BinaryFormatter();
            //MemoryStream stream = new MemoryStream();
            //Scans _data = null;
            //bformatter = new BinaryFormatter();
            //stream = new MemoryStream(lstData);
            //DataTable dt = (DataTable)bformatter.Deserialize(stream);
            //stream.Close();

            List<Scans> lst = new List<Scans>();
            Scans _scan = null;
            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    _data = new Scans();
            //    _data.FirstName = Convert.ToString(dt.Rows[i][0]);
            //    _data.LastName = Convert.ToString(dt.Rows[i][1]);
            //    _data.Grade = Convert.ToInt32(dt.Rows[i][2]);
            //    lst.Add(_data);
            //}

            // Read sample data from CSV file
            using (CsvFileReader reader = new CsvFileReader( new MemoryStream(lstData)))
            {
                int count=0;
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row))
                {
                    if (count > 0)
                    {
                        
                        _scan = new Scans();
                        _scan.StudentIdNumber = row.Count>1 ? Utility.GetInt(row[0]):0;
                        _scan.FirstName = row.Count>=2? Utility.GetString(row[1]):"";
                        _scan.LastName = row.Count>=3? Utility.GetString(row[2]):"";
                        _scan.Grade = row.Count>=4 ?Utility.GetInt(row[3]):0;
                        _scan.ValidityCode = row.Count>=5? Utility.GetInt(row[4]):1;
                        _scan.Note1 = row.Count>=5? Utility.GetString(row[5]):"";
                        _scan.Note2 = row.Count>=7? Utility.GetString(row[6]):"";
                        _scan.Note3 = row.Count>=8? Utility.GetString(row[7]):"";
                        _scan.Note4 = row.Count>=9? Utility.GetString(row[8]):"";
                        lst.Add(_scan);
                    }
                    count++;
                }
            }

            return lst;
        }
        public static byte[] StrToByteArray(string str)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetBytes(str);
        }
        public static string ByteArrayToStr(byte[] barr)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetString(barr, 0, barr.Length);
        }
        internal string CreateDatabase(ref int nwdbId)
        {
            DatabaseOperations _dbOp = new DatabaseOperations();
            return _dbOp.CreateNewDatabase(DBName, IsCaseSensitiveValidation, CreatedBy, ScanDataList, ServiceDetails, ref nwdbId);
        }
        internal string AddScanData()
        {
            DatabaseOperations _dbOp = new DatabaseOperations();
            return "";// _dbOp.AddScanData(CreatedBy, DbId, ScanDataList[0]);
        }
        internal string RenameDB()
        {
            DatabaseOperations _dbOp = new DatabaseOperations();
            return _dbOp.RenameDatabase(CreatedBy, DbId, DBName);
        }
        internal string DeteleDB()
        {
            DatabaseOperations _dbOp = new DatabaseOperations();
            return _dbOp.DeleteDatabase(CreatedBy, DbId);
        }
        internal DatabaseDetails GetDatabaseDetails()
        {
            DatabaseOperations _dbOp = new DatabaseOperations();
            return _dbOp.GetDatabaseDetails(CreatedBy, DbId);
        }
        internal string AssociateServiceToDb()
        {
            DatabaseOperations _dbOp = new DatabaseOperations();
            return _dbOp.AssociateServicToDatabase(DbId, ServiceDetails, CreatedBy);
        }
        internal List<int> GetDBIDList(int clientId)
        {
            DatabaseOperations op = new DatabaseOperations();
            return op.GetDBIDList(clientId);
        }
        internal string GetTableData()
        {
            DatabaseOperations op = new DatabaseOperations();          
            
            return DataTableToCSV(op.GetDBIDList(DbId, CreatedBy));
          
        }
        public static string DataTableToCSV(DataTable table)
        {
            var result = new StringBuilder();
            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(table.Columns[i].ColumnName);
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }

            foreach (DataRow row in table.Rows)
            {
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    result.Append(row[i].ToString());
                    result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
                }
            }

            return result.ToString();
        }


        internal string UpdateScanData(ScanData data)
        {
            DatabaseOperations _dbOp = new DatabaseOperations();
            // _dbOp.AddScanData(CreatedBy, DbId, ScanDataList[0]);
            return _dbOp.UpdateScans(data, DbId, CreatedBy);
        }

        public string HashCode { get; set; }

        internal string DeleteScanData(string barCodeValue)
        {
            DatabaseOperations _dbOp = new DatabaseOperations();
            return _dbOp.DeleteScanData(DbId, CreatedBy, barCodeValue, HashCode);
        }

        internal string AddScanData(int dbId, int loggedInUserId, Scans scanData)
        {
            return new DatabaseOperations().AddScanData(dbId, loggedInUserId, scanData);
        }

        internal string EmptyDatabase(int clientId, int dbId, string hashCode)
        {
            return new DatabaseOperations().EmptyDatabase(clientId,dbId,hashCode);
        }
    }

    public class ScanData
    {
        private int clientId;
        private int userId;
        private string hashCode;

        public ScanData(int clientId, int userId, string hashCode)
        {
            // TODO: Complete member initialization
            this.clientId = clientId;
            this.userId = userId;
            this.hashCode = hashCode;
        }

        public ScanData()
        {
            // TODO: Complete member initialization
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int OldStudentIdNumber { get; set; }
        public int StudentIdNumber { get; set; }
        public int Validity { get; set; }
        public int Grade { get; set; }
        public string Note1 { get; set; }
        public string Note2 { get; set; }
        public string Note3 { get; set; }
        public string Note4 { get; set; }
        internal List<Scans> GetScans()
        {
            return null;
        }
    }
}